<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      v-show="showSearch"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="公司名稱" prop="customerName">
        <el-input
          v-model="queryParams.customerName"
          placeholder="请输入公司名稱"
          clearable
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="聯繫人" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入聯繫人名称"
          clearable
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="业务员" prop="nickName">
        <el-input
          v-model="queryParams.nickName"
          placeholder="请输入业务员"
          clearable
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>

      <el-form-item label="創建時間" style="width: 308px">
        <el-date-picker
          v-model="dateRange"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          start-placeholder="開始日期"
          end-placeholder="結束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          v-hasPermi="['system:business:add']"
          @click="handleAdd"
          >新增</el-button
        >
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:business:update']"
          >修改</el-button
        >
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:business:delete']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="Upload"
          @click="handleImport"
          v-hasPermi="['system:business:import']"
          >導入</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['system:business:export']"
          >導出</el-button
        >
      </el-col>

      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <!-- 表格数据 -->
    <el-table
      v-loading="loading"
      :data="businessList"
      :border="true"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="公司名稱"  prop="customerName">
        <template #default="scope">
          <el-link :underline="false" type="primary" @click="openDialog(scope.row)">
            {{ scope.row.customerName }}
          </el-link>
        </template>
      </el-table-column>
      <el-table-column
        label="縣/市"
        prop="countiesCities"
        :show-overflow-tooltip="true"
        width="120"
      />
      <el-table-column
        label="聯繫人"
        align="center"
        :show-overflow-tooltip="true"
      >
        <template #default="scope">
          <router-link
            :to="'/business/business-data/index/' + scope.row.id"
            class="link-type"
          >
            <span>{{ scope.row.name }}</span>
          </router-link>
        </template>
      </el-table-column>

      <!-- <el-table-column
      label="联络人"
      width="120"
      :show-overflow-tooltip="true"
    >
      <template v-slot="{ row }">
        <el-link type="primary" @click="handleAuthbusiness(row)">
          {{ row.name }}
        </el-link>
      </template>
    </el-table-column> -->

      <el-table-column
        label="ERP簡稱"
        align="center"
        prop="abbreviation"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="公司地址"
        align="center"
        width="80"
        prop="customeraddress"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="公司电话"
        align="center"
        width="80"
        prop="companyTel"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="公司類別"
        align="center"
        width="80"
        prop="countomtype"
        :show-overflow-tooltip="true"
      />
      <!-- <el-table-column label="感興趣產品" align="center"  prop="interest"  :show-overflow-tooltip="true"/> -->
      <!-- <el-table-column label="公司簡介" align="center" width="80"  prop="customerprofile"  :show-overflow-tooltip="true"/>
      <el-table-column label="來源途徑" align="center"  prop="countomsource"  :show-overflow-tooltip="true" /> -->

      <el-table-column
        label="业务员"
        align="center"
        prop="nickName"
        :show-overflow-tooltip="true"
      />

      <el-table-column
        label="創建時間"
        prop="createTime"
        :show-overflow-tooltip="true"
      >
      </el-table-column>
      <!-- <el-table-column label="創建人"  prop="createUser"></el-table-column> -->
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-tooltip content="拜訪" placement="top">
            <el-button
              link
              type="primary"
              icon="Bicycle"
              @click="handleAuthbusiness(scope.row)"
              v-hasPermi="['system:business:add']"
            ></el-button>
          </el-tooltip>

          <el-tooltip content="案件" placement="top">
            <el-button
              link
              type="primary"
              icon="List"
              @click="handlecase(scope.row)"
              v-hasPermi="['system:case:query']"
            ></el-button>
          </el-tooltip>
          <el-tooltip content="修改" placement="top">
            <el-button
              link
              type="primary"
              icon="Edit"
              @click="handleUpdate(scope.row,true)"
              v-hasPermi="['system:business:update']"
            ></el-button>
          </el-tooltip>
          <el-tooltip content="删除" placement="top">
            <el-button
              link
              type="primary"
              icon="Delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['system:business:delete']"
            ></el-button>
          </el-tooltip>

          <!-- <el-tooltip content="数据权限" placement="top" v-if="scope.row.roleId !== 1">
                 <el-button link type="primary" icon="CircleCheck" @click="handleDataScope(scope.row)" v-hasPermi="['system:role:edit']"></el-button>
               </el-tooltip>
               <el-tooltip content="分配用户" placement="top" v-if="scope.row.roleId !== 1">
                 <el-button link type="primary" icon="User" @click="handleAuthUser(scope.row)" v-hasPermi="['system:role:edit']"></el-button>
               </el-tooltip> -->
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改角色配置对话框 -->
    <el-dialog :title="title" v-model="open" width="1200px" append-to-body>
      <el-form
        ref="addclientele"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-row>
          <el-col :span="8">
            <el-form-item label="客戶名稱:" prop="customerName">
              <el-input
                style="width: 97%"
                v-model="form.customerName"
                placeholder="请输入客戶名稱"
              />
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="ERP簡稱:" prop="abbreviation">
              <el-input
                style="width: 97%"
                v-model="form.abbreviation"
                placeholder="请输入客戶簡稱"
              />
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="縣/市:" prop="countiesCities">
              <el-cascader
                v-model="form.countiesCities"
                :options="formattedOptions"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="8">
            <el-form-item label="公司地址:" prop="customeraddress">
              <el-input
                style="width: 97%"
                v-model="form.customeraddress"
                placeholder="请输入公司地址"
              />
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="公司电话:" prop="companyTel">
              <el-input
                style="width: 97%"
                v-model="form.companyTel"
                placeholder="请输入公司电话"
              />
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="公司類別:" prop="countomtype">
              <el-cascader
                v-model="form.countomtype"
                :options="business_category"
                :props="{ emitPath: false, value: 'value', label: 'label' }"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="8">
            <el-form-item label="感興趣產品:" prop="interest">
              <el-select
                style="width: 97%"
                clearable
                multiple
                v-model="form.interest"
                placeholder="选择感興趣產品"
              >
                <el-option
                  v-for="item in crm_lamps"
                  :key="item.value"
                  :label="item.label"
                  :value="item.label"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="公司簡介:" prop="customerprofile">
              <el-input
                style="width: 97%"
                type="textarea"
                v-model="form.customerprofile"
                placeholder="请输入公司簡介"
              />
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="來源途徑:" prop="countomsource">
              <el-cascader
                v-model="form.countomsource"
                :options="business_source"
                :props="{ emitPath: false, value: 'value', label: 'label' }"
                clearable
              />
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="規模" prop="scale">
              <template #label>
                <span>
                  <el-tooltip
                    content="Ａ 20人以上Ｂ 10~20人Ｃ 5~10D 個體戶"
                    placement="top"
                  >
                    <el-icon><question-filled /></el-icon>
                  </el-tooltip>
                  规模
                </span>
              </template>
              <el-select
                style="width: 97%"
                v-model="form.scale"
                placeholder="选择規模"
              >
                <el-option
                  v-for="item in crm_scale"
                  :key="item.value"
                  :label="item.label"
                  :value="item.label"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="公司網站:" prop="customerweb">
              <el-input
                style="width: 97%"
                v-model="form.customerweb"
                placeholder="请输入公司網站"
              >
                <template #prepend>Http://</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- <el-row>
      <el-col :span="12">
        <el-form-item label="主營項目" prop="project">
          <el-select   clearable multiple v-model="form.project" placeholder="选择主營項目">
            <el-option
              v-for="item in crm_project"
              :key="item.value"
              :label="item.label"
              :value="item.label"
            />
          </el-select>
        </el-form-item>
</el-col>

<el-col :span="12">
        <el-form-item label="常用燈具" prop="luminaire">
          <el-select  clearable multiple v-model="form.luminaire" placeholder="选择常用燈具">
            <el-option
              v-for="item in crm_lamps"
              :key="item.value"
              :label="item.label"
              :value="item.label"
            />
          </el-select>
        </el-form-item>
        </el-col>
        </el-row>


        
    <el-row>
      <el-col :span="12">
        <el-form-item label="規模" prop="scale">
          <template #label>
            <span>
              <el-tooltip
                content="Ａ 20人以上Ｂ 10~20人Ｃ 5~10D 個體戶"
                placement="top"
              >
                <el-icon><question-filled /></el-icon>
              </el-tooltip>
              规模
            </span>
          </template>
          <el-select v-model="form.scale" placeholder="选择規模">
            <el-option
              v-for="item in crm_scale"
              :key="item.value"
              :label="item.label"
              :value="item.label"
            />
          </el-select>
        </el-form-item>
      </el-col>

      <el-col :span="12">
        <el-form-item label="拜訪分類" prop="classification">
          <template #label>
            <span>
              <el-tooltip
                content="Ａ 可持續聯繫發展Ｂ 有拜訪但無消息Ｃ 尚未拜訪Ｄ 沒機會"
                placement="top"
              >
                <el-icon><question-filled /></el-icon>
              </el-tooltip>
              拜訪分類
            </span>
          </template>
          <el-select  clearable v-model="form.classification" placeholder="选择拜訪分類">
            <el-option
              v-for="item in crm_classify"
              :key="item.value"
              :label="item.label"
              :value="item.label"
            />
          </el-select>
        </el-form-item>
        </el-col>
      </el-row>
        <el-form-item label="客戶等級" prop="client_grade">
          <template #label>
            <span>
              <el-tooltip
                content="Ａ 有案件持續發展（已下單＋未下單）Ｂ有興趣但無案件Ｃ 沒興趣或產品不符Ｄ 非目標客群"
                placement="top"
              >
                <el-icon><question-filled /></el-icon>
              </el-tooltip>
              客戶等級
            </span>
          </template>
          <el-select  clearable v-model="form.clientGrade" placeholder="选择客戶等級">
            <el-option
              v-for="item in crm_class"
              :key="item.value"
              :label="item.label"
              :value="item.label"
            />
          </el-select>
        </el-form-item> -->

        <div class="contact-container" v-show="show">
          <div
            class="contact-item"
            v-for="(contact, index) in contacts"
            :key="index"
          >
            <el-form-item
              :label="'聯繫人姓名' + (index + 1)"
              :rules="rules"
              required
            >
              <el-input
                v-model="contact.name"
                placeholder="请输入聯繫人姓名"
              ></el-input>
            </el-form-item>
            <el-form-item :label="'聯繫人職稱' + (index + 1)">
              <el-input
                v-model="contact.contactPosition"
                placeholder="请输入職稱"
              ></el-input>
            </el-form-item>

            <el-form-item :label="'聯繫人電話' + (index + 1)">
              <el-input
                v-model="contact.contactNumber"
                placeholder="请输入聯繫人電話"
              ></el-input>
            </el-form-item>

            <el-form-item :label="'E-Mail'">
              <el-input
                v-model="contact.contactAddress"
                placeholder="请输入聯繫人地址"
              ></el-input>
            </el-form-item>

            <el-button
              class="iconfont icon-jiahao"
              type="primary"
              @click="addContact"
            ></el-button>

            <el-button
              v-show="contacts.length > 1 && index > 0"
              class="iconfont icon-jianhao"
              type="primary"
              @click="removeContact(index)"
            ></el-button>
          </div>
        </div>

        <el-row>
          <el-col :span="8" class="align-right">
            <el-form-item label="业务员:" prop="nickName">
              <!-- <el-input style="width: 97%" v-model="form.nickName"  /> -->
              <el-select  v-model="form.nickName" placeholder="选择业务员">
                <el-option
              v-for="user in userList"
              :key="user.nickNameTW"
             :label="user.nickNameTW"
             :value="user.nickNameTW
"
  />
            </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">確 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 用户導入对话框 -->
    <el-dialog
      :title="upload.title"
      v-model="upload.open"
      width="400px"
      append-to-body
    >
      <el-upload
        ref="uploadRef"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <div class="el-upload__tip">
              <el-checkbox
                v-model="upload.updateSupport"
              />是否更新已经存在的用户数据
            </div>
            <span>仅允许導入xls、xlsx格式文件。</span>
            <el-link
              type="primary"
              :underline="false"
              style="font-size: 12px; vertical-align: baseline"
              @click="importTemplate"
              >下载模板</el-link
            >
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>










    <!-- 查看联系人 -->
    <el-drawer
    v-model="table"   
    direction="rtl"
    title="公司信息明細"
    size="60%"
  >
  <el-descriptions >
    <el-descriptions-item label="客戶名稱:">{{ form.customerName }}</el-descriptions-item>
    <el-descriptions-item label="ERP簡稱:">{{ form.abbreviation }}</el-descriptions-item>
    <el-descriptions-item label="縣/市:">{{ form.countiesCities }}</el-descriptions-item>
    <el-descriptions-item label="公司地址:">
      <el-tag size="small">{{ form.customeraddress }}</el-tag>
    </el-descriptions-item>
    <el-descriptions-item label="公司电话:">
 {{ form.companyTel }}
    </el-descriptions-item>
    <el-descriptions-item label="公司類別:">{{ form.countomtype }}</el-descriptions-item>
    <el-descriptions-item label="感興趣產品:">{{ form.interest }}</el-descriptions-item>
   
    <el-descriptions-item label="來源途徑:">{{ form.countomsource }}</el-descriptions-item>
    <el-descriptions-item label="規模:">{{ form.scale }}</el-descriptions-item>
    <el-descriptions-item label="公司網站:">{{ form.customerweb }}</el-descriptions-item>
    <el-descriptions-item label="公司簡介:">{{ form.customerprofile }}</el-descriptions-item>

  </el-descriptions>
  <br> <br> <br>
  <el-table  :data="contactsList"    >
        <el-table-column label="联系人名称" prop="name" :show-overflow-tooltip="true" />
        <el-table-column label="联系人職稱" prop="contactPosition" :show-overflow-tooltip="true" />
        <el-table-column label="联系人电话" prop="contactNumber" :show-overflow-tooltip="true" />
        <el-table-column label="e-mail" prop="contactAddress" :show-overflow-tooltip="true" />
        <el-table-column label="创建时间" align="center" prop="createTime" width="180">
           <template #default="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
           </template>
        </el-table-column>
     </el-table>
    <div class="no-print" style="margin-top: 20%;">
      <el-button type="primary" @click="exportAllData">导出所有数据</el-button>
      <el-button type="info" @click="printData">打印</el-button>
    </div>
   
    </el-drawer>
  </div>
</template>
 
 <script setup name="business">
import {
  addbusiness,
  updatebusiness,
  listbusiness,
  delbusiness,
  getbusiness,
  getTaiwanEmployee,
} from "@/api/business/add.js";

import {
   listcontacts,
} from "@/api/business/contacts.js";
import {
    listUser,
  } from "@/api/system/user.js";
  

import { ref, watch } from "vue";
import { useCitySelect } from "@/api/business/addressJson";
import { getToken } from "@/utils/auth";
import { getUserProfile } from "@/api/system/user";
import { fa } from "element-plus/es/locales.mjs";

const router = useRouter();
const { proxy } = getCurrentInstance();
const show = ref(true);
const {
  sys_normal_disable,
  crm_project,
  crm_lamps,
  crm_scale,
  crm_classify,
  crm_class,
  business_category,
  business_source,
} = proxy.useDict(
  "sys_normal_disable",
  "crm_project",
  "crm_lamps",
  "crm_scale",
  "crm_classify",
  "crm_class",
  "business_category",
  "business_source"
);

/*** 用户導入参数 */
const upload = reactive({
  // 是否显示弹出层（用户導入）
  open: false,
  // 弹出层标题（用户導入）
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + getToken() },
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/business/importData",
});

/** 導入按钮操作 */
function handleImport() {
  upload.title = "用户導入";
  upload.open = true;
}

/** 下载模板操作 */
function importTemplate() {
  proxy.download(
    "business/importTemplate",
    {},
    `客户模板_template_${new Date().getTime()}.xlsx`
  );
}
/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true;
};
/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  upload.open = false;
  upload.isUploading = false;
  proxy.$refs["uploadRef"].handleRemove(file);
  proxy.$alert(
    "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
      response.msg +
      "</div>",
    "導入结果",
    { dangerouslyUseHTMLString: true }
  );
  getList();
};

/** 导出所有数据操作 */
function exportAllData() {
  const data = [
    ["客戶名稱:", form.value.customerName],
    ["ERP簡稱:", form.value.abbreviation],
    ["縣/市:", form.value.countiesCities],
    ["公司地址:", form.value.customeraddress],
    ["公司电话:", form.value.companyTel],
    ["公司類別:", form.value.countomtype],
    ["感興趣產品:", form.value.interest],
    ["來源途徑:", form.value.countomsource],
    ["規模:", form.value.scale],
    ["公司網站:", form.value.customerweb],
    ["公司簡介:", form.value.customerprofile],
  ];
  // 添加联系人数据
  data.push(["联系人名称:", "联系人職稱:", "联系人电话:", "e-mail:", "创建时间:"]);
  contactsList.value.forEach(contact => {
    data.push([
      contact.name,
      contact.contactPosition,
      contact.contactNumber,
      contact.contactAddress,
      contact.createTime
    ]);
  });

  // 转换为 CSV 格式并添加 BOM
  const csvContent = "\uFEFF" + data.map(row => row.join(",")).join("\n");

  // 创建一个下载链接
  const encodedUri = encodeURI("data:text/csv;charset=utf-8," + csvContent);
  const link = document.createElement("a");
  link.setAttribute("href", encodedUri);
  link.setAttribute("download", `${form.value.customerName}公司详情.csv`);
  document.body.appendChild(link); // 需要将链接添加到 DOM 中

  link.click(); // 模拟点击下载
  document.body.removeChild(link); // 下载后移除链接
}

function printData() {
  const printContent = document.querySelector('.el-drawer').cloneNode(true); // 获取要打印的内容并克隆
  const buttons = printContent.querySelector('.no-print'); // 查找包含按钮的元素
  if (buttons) {
    buttons.remove(); // 移除按钮
  }
  
  const newWindow = window.open('', '_blank'); // 打开新窗口
  newWindow.document.write('<html><head><title>打印内容</title></head><body>');
  
  // 将内容写入新窗口
  newWindow.document.write(printContent.innerHTML);
  
  newWindow.document.write('</body></html>');
  newWindow.document.close();
  newWindow.print(); // 调用打印
  newWindow.close(); // 打印后关闭窗口
}
/** 提交上传文件 */
function submitFileForm() {
  proxy.$refs["uploadRef"].submit();
}

// 使用 useCitySelect 函数
const { taiwanCities } = useCitySelect();

// 初始化格式化的选项数据
const formattedOptions = ref([]);
const businessList = ref([]);
const contactsList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const dateRange = ref([]);
const table =ref(false);
const userList = ref([]);
const shows = ref(false);
const contacts = ref([
  {
    name: "",
  },
]);

const  queryContacts = ref({
    businessId: "",
  })

const data = reactive({
  form: {
    interest: [],
    //   project: [], // 确保这里是一个数组
    // luminaire: [] // 确保这里是一个数组
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    roleName: undefined,
    roleKey: undefined,
    status: undefined,
  },
 
  rules: {
    customerName: [
      { required: true, message: "客户名称不能为空", trigger: "blur" },
    ],
    countiesCities: [
      { required: true, message: "县/区不能为空", trigger: "blur" },
    ],
    countomsource: [
      { required: true, message: "來源途徑不能为空", trigger: "blur" },
    ],
    countomtype: [
      { required: true, message: "公司類別不能为空", trigger: "blur" },
    ],
    contacts: {
      type: "array",
      required: true,
      message: "至少需要一个聯繫人",
      trigger: "blur",
    },
    name: [{ required: true, message: "聯繫人姓名不能为空", trigger: "blur" }],
  },
});

const { queryParams, form, rules } = toRefs(data);

/** 查询列表 */
function getList() {
  loading.value = true;
  listbusiness(proxy.addDateRange(queryParams.value, dateRange.value))
    .then((response) => {
      businessList.value = response.rows;
      businessList.value = businessList.value.map((item) => {
        const parts = item.countiesCities.split("-");
        item.countiesCities = [parts[0], parts[1]];
        return item;
      });
      total.value = response.total;
      loading.value = false;
    })
    .catch((error) => {
      loading.value = false;
    });
}

//打开弹窗
function openDialog(row) {
 table.value=true;
  shows.value = false;
 handleUpdate(row,shows);
 getListContacts(row)
}

 /** 查询用户列表 */
 function getUserList() {

  getTaiwanEmployee().then(response => {
 userList.value = response.rows;

});
 }

//根据id查询联系人
function getListContacts(row) {
  queryContacts.businessId = row.id;
 listcontacts(queryContacts).then(response => {
   contactsList.value = response.rows;
 });
}


/** 查看联系人 */
function handleAuthbusiness(row) {
  router.push("/business/business-journal/index/" + row.id);
}

// 格式化选项数据
function formatOptions(cities) {
  const result = [];

  for (const province in cities) {
    if (cities.hasOwnProperty(province)) {
      const provinceObj = {
        value: province,
        label: province,
        children: [],
      };

      const cityList = cities[province];
      if (Array.isArray(cityList)) {
        for (const city of cityList) {
          provinceObj.children.push({
            value: city.value,
            label: city.name,
            children: [],
          });

          // 如果城市下还有区，则继续添加
          if (cities[city.value]) {
            for (const district of cities[city.value]) {
              provinceObj.children
                .find((c) => c.value === city.value)
                .children.push({
                  value: district.value,
                  label: district.name,
                });
            }
          }
        }
      }

      result.push(provinceObj);
    }
  }

  return result;
}

// 监听 taiwanCities 的变化并重新格式化选项
watch(taiwanCities, () => {
  formattedOptions.value = formatOptions(taiwanCities.value);
});

// 初始化格式化的选项
formattedOptions.value = formatOptions(taiwanCities.value);

// 删除联系人
function removeContact(index) {
  contacts.value.splice(index, 1);
}
// 添加联系人
function addContact() {
  contacts.value.push({
    name: "",
    contactNumber: "",
    contactddress: "",
  });
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}
/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

function handlecase(row) {
  // 使用 router.push 导航到指定的路由
  router.push("/business/auth/index/" + row.id);
}
/** 删除按钮操作 */
function handleDelete(row) {
  const id = row.id || ids.value;
  proxy.$modal
    .confirm('是否确认删除为"' + id + '"的数据项?')
    .then(function () {
      return delbusiness(id);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}
/** 導出按钮操作 */
function handleExport() {
  proxy.download(
    "business/export",
    {
      ...queryParams.value,
    },
    `business_${new Date().getTime()}.xlsx`
  );
}
/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}
/** 角色状态修改 */
function handleStatusChange(row) {
  let text = row.status === "0" ? "启用" : "停用";
  proxy.$modal
    .confirm('确认要"' + text + '""' + row.roleName + '"角色吗?')
    .then(function () {
      return changeRoleStatus(row.roleId, row.status);
    })
    .then(() => {
      proxy.$modal.msgSuccess(text + "成功");
    })
    .catch(function () {
      row.status = row.status === "0" ? "1" : "0";
    });
}
/** 更多操作 */
function handleCommand(command, row) {
  switch (command) {
    case "handleDataScope":
      handleDataScope(row);
      break;
    case "handleAuthUser":
      handleAuthUser(row);
      break;
    default:
      break;
  }
}

function reset() {
  form.value = {};
  contacts.value = [
    {
      name: "",
    },
  ];
  proxy.resetForm("addclientele");
}
/** 添加角色 */
function handleAdd() {
  reset();
  show.value = true;
  getUserProfile().then((response) => {
    form.value.nickName = response.data.nickName; // 直接赋值
  });

  open.value = true;
  title.value = "添加客戶";
}
/** 修改角色 */
function handleUpdate(row,shows) {
  reset();

  show.value = false;
  const id = row.id || ids.value;
  getbusiness(id).then((response) => {
    const data = response.data;

    // 解析 project 和 luminaire 字段
    data.interest = data.interest ? data.interest.split(",") : [];
    // data.project = data.project ? data.project.split(',') : [];
    // data.luminaire = data.luminaire ? data.luminaire.split(',') : [];

    // 将解析后的数据赋值给 form
    form.value = data;

  
  
    
    if(shows.value==false){
      open.value = false;
  }else{
     open.value=true;
  }
  
    // 将 row 中的 countiesCities 通过 '-' 分割并复制到 countiesCities 数组中

    if (typeof form.value.countiesCities === "string") {
      form.value.countiesCities = form.value.countiesCities.split("-");
    }
    contacts.value[0].name = form.value.name;

    title.value = "修改公司";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["addclientele"].validate((valid) => {
    if (valid) {
      // 提取contacts数组，并重新命名为contactse
      const contactse = contacts.value;
      // 合并数据
      // 提取 project 数组
      // 检查 project 是否为数组
      if (Array.isArray(form.value.interest)) {
        // 将项目数组转换成逗号分隔的字符串
        const interestString = form.value.interest.join(",");
        form.value.interest = interestString;
      }

      // if (Array.isArray(form.value.project)) {
      //   // 将项目数组转换成逗号分隔的字符串
      //   const projectString = form.value.project.join(',');
      //   form.value.project = projectString;
      // }

      // // 检查 luminaire 是否为数组
      // if (Array.isArray(form.value.luminaire)) {
      //   // 将灯具数组转换成逗号分隔的字符串
      //   const luminaireString = form.value.luminaire.join(',');
      //   form.value.luminaire = luminaireString;
      // }
      // 添加判断，检查第一个联系人的姓名是否为空

      const mergedData = { ...form.value, contactse };
      if (form.value.id != undefined) {
        updatebusiness(mergedData).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        if (!contactse[0].name) {
          proxy.$modal.msgError("请填写第一个联系人的姓名");
          return; // 终止提交
        }
        addbusiness(mergedData).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}
/** 取消按钮 */
function cancel() {
  open.value = false;
}

// 在组件挂载时调用 getUser 和 getList 方法
onMounted(() => {
  getList();
  getUserList();
});
</script>

<style scoped>
@media print {
  .no-print {
    display: none; /* 隐藏带有 no-print 类的元素 */
  }
}
.align-right {
  margin-left: auto;
  margin-top: 3%;
}
.linkman-input-group {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.linkman-input-group .el-input {
  flex: 1;
  margin-right: 10px;
}
.contact-container {
  display: flex;
  flex-wrap: wrap;
  gap: 10px; /* 项目之间的间距 */
}

.contact-item {
  flex: 1 1 calc(33% - 3px); /* 每个项目占50%的宽度，减去间距 */
  max-width: calc(33% - 3px); /* 最大宽度也是50%，减去间距 */
  box-sizing: border-box;
}
</style>